package com.example.flshtarvel.component;

import com.example.flshtarvel.entity.Article;
import com.example.flshtarvel.entity.Image;
import com.example.flshtarvel.service.ImageService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;

@Component
public class DownLoadImage {
    @Autowired
    private ImageService imageService;

//    @Autowired
//    private ImageArticleMapService imageArticleMapService;

    public static DownLoadImage downLoadImage;
    @PostConstruct
    public void init(){
        downLoadImage = this;
    }

    //删除图片资源(批量操作)
    public void executeDownloadImageBatch(String articleId){
        System.out.println("批量删除图片");
        try {
            //图片文件路径
            String path = ResourceUtils.getURL("classpath:static/").getPath() + "image/";
            List<Image> imageList = downLoadImage.imageService.selectImageById(articleId);
            for (Image image : imageList) {
                //图片名称
                String fileName = image.getImageName();
                //生成图片文件
                File file = new File(path + fileName);
                if (file.exists()) {
                    if (file.delete()) {
                        //删除图片表（iamge）数据
                        downLoadImage.imageService.deleteImage(image.getImageId());
                        System.out.println(image.getImageName());
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //删除图片资源（单个操作）
    public void executeDownloadImage(Image image, Article article){
        try {
            //图片路径
            String path = ResourceUtils.getURL("classpath:static/").getPath() + "image/";
            //图片名称
            String fileName = image.getImageName();
            //生成图片文件
            File file = new File(path+fileName);
            if(file.exists()){
                if(file.delete()){
                    //删除图片表数据
                    downLoadImage.imageService.deleteImage(image.getImageId());
                    System.out.println(image.getImageName());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
